// -----------------------------------------------------------------------
//  <copyright file="CommandLineBuilder.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-11-27 0:05</last-date>
// -----------------------------------------------------------------------

using System.Diagnostics;
using System.Runtime.Versioning;


namespace DaprPlus.Development;

public class CommandLine
{
    public CommandLine(string app) : this(app, "")
    { }

    public CommandLine(string app, CommandLineArgs args) : this(app, args.ToString())
    { }

    public CommandLine(string app, string args)
    {
        App = app;
        Args = args;
    }

    public string App { get; }

    public string Args { get; }

    public override string ToString() => Args.IsNullOrEmpty() ? App : $"{App} {Args}";

    public Process Run()
    {
        if (Args.IsNullOrEmpty())
        {
            return Process.Start(App);
        }
        return Process.Start(App, Args);
    }

    [SupportedOSPlatform("windows")]
    public Process Run(string processName, string exceptToken)
    {
        var processes = Process.GetProcessesByName(processName);
        if (processes.Any(p => p.GetCommandLineArgs().Contains(exceptToken) == false))
        {
            return Process.Start(App, Args);
        }

        return null!;
    }
}
